<template>
  <div class="page-container">
    <div ref="plantRef" class="container-charts"></div>
  </div>
</template>
  
  <script>
import { pie } from "../request/api";
export default {
  data() {
    return {
      seriesData: [],
    };
  },
  computed:{
    getTheme(){
      return this.$store.state.theme
    }
  },
  watch:{
    getTheme(){
      this.info.dispose()
      this.initEcharts()
      this.getData()
      this.screen()
    }
  },
  mounted() {
    this.initEcharts();
    this.getData();
    this.screen();
    window.addEventListener("resize", this.screen);
  },
  destroyed() {
    window.removeEventListener("resize", this.screen);
  },
  methods: {
    //封装一个初始化图表的事件
    initEcharts() {
      let dom = this.$refs.plantRef;
      let myChart = this.$echarts.init(dom,this.getTheme);
      this.info = myChart;
      let options = {
        title: {
          text: "种植农作物面积统计", //主标题
        },
        series: this.seriesData,
      };
      myChart.setOption(options);
    },
    //抽离数据
    async getData() {
      //直接调用接口
      let res = await pie();
      console.log(res);
      this.seriesData = res.data.map((item, i) => {
        console.log(item);
        return {
          value: item.value,
          name: item.name,
        };
      });
      console.log(this.seriesData);
      this.info.setOption({
        legend: {
          data: this.seriesData.map((item) => item),
          top: 30,
        },
        series: [
          {
            type: "pie",
            radius: 100,
            data: this.seriesData.map((item) => item),
          },
        ],
      });
    },
    screen() {
      this.info.resize();
      let width = this.$refs.plantRef.offsetWidth;
      let num = (width / 100) * 5;
      let option = {
        title: {
          textStyle: {
            fontSize: num,
          },
        },
      };
      this.info.setOption(option);
    },
  },
};
</script>
  
  <style lang="less" scoped></style>
  